package com.xxh.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.blog.entity.vo.EssayVo;
import com.xxh.blog.service.SearchService;
import com.xxh.blog.service.essayService;
import com.xxh.blog.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class indexController {

    @Resource
    essayService essayService;

    @Autowired
    SearchService searchService;

    @RequestMapping({"/","","index"})
    public String index(Model model, HttpServletRequest request){

        model.addAttribute("curCategoryID",0);
        Integer curpage = request.getParameter("curpage")==null?1:Integer.valueOf(request.getParameter("curpage"));
        Integer size = request.getParameter("size")==null?5:Integer.valueOf(request.getParameter("size"));
        Page page=new Page(curpage,size);

        /**
         * 获取置顶文章
         *
         */
        IPage<EssayVo> paging = essayService.paging(new Page(), null, 1, null, null, null);
        model.addAttribute("TopEssays",paging);


        /**
         * 获取所有的文章
         *
         * 参数1 分页信息
         * 参数2 查询条件：文章分类，是否置顶，查询的用户，是否精选
         */
        IPage<EssayVo> result = essayService.paging(page, null, null, null, null, null);
        System.out.println(result.toString());
        model.addAttribute("allEssays",result);

        return "index";
    }


    /**
     * 搜索功能
     * @param q 搜索的内容
     * @return
     */
    @RequestMapping("/search")
    public String search(@RequestParam(name = "q") String q , Model model, HttpServletRequest request){
        System.out.println(q);
        Integer curpage = request.getParameter("curpage") == null ? 1 : Integer.parseInt(request.getParameter("curpage"));
        Integer size = request.getParameter("size") == null ? 5 : Integer.parseInt(request.getParameter("size"));


        IPage page = searchService.search(new Page(curpage, size), q);
        System.out.println(page);
        model.addAttribute("q",q);
        model.addAttribute("searchDate",page);
        return "search";
    }

    @RequestMapping("/restsearch")
    @ResponseBody
    public Result searchRest(@RequestParam(name = "q") String q){
        IPage page = searchService.search(new Page(1, 10), q);
        return Result.ok().put("data",page);
    }
}
